<template>
  <div class="species-observation-detail">
    <CardBox title="物候观测详情"></CardBox>
    <div class="content-container">
      <div class="species-observation-detail-content">
        <div class="detail-layout" v-if="record">
          <!-- 左侧图片 -->
          <div class="detail-image" v-if="record.fileType==='video'">
            <video
                    :src="record.fileUrl"
                    alt="物种图片"
                    controls="false"
                    autoplay loop
                    preload="auto"
            />
          </div>
          <div class="detail-image" v-else-if="record.fileType==='image'">
            <img class="img" :src="record.img" alt="默认图片">
          </div>
          <div v-else-if="record.fileType === 'audio'" class="content-audios">
            <div class="audio-card" id="card1" @click="playAudio()" >
              <div class="audio-img">
                <img :src="record.avatar" alt="音乐封面" class="audio-image">
              </div>
              <div class="audio-content">
                <div class="audio-info">
                  <h3>{{record.scientificName}}</h3>
                  <div class="time-display" id="time1">0:00 / 0:00</div>
                </div>
                <div class="waveform-container">
                  <div class="waveform" ref="waveform1" id="waveform1"></div>
                  <div class="progress-bar" id="progress1"></div>
                </div>
              </div>
            </div>
          </div>
          <!-- 右侧信息 -->
          <div class="detail-info">
            <div class="info-item">
              <span class="info-label">名称：</span>
              <span class="info-value">{{ record.plantName }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">物候期：</span>
              <span class="info-value">{{ record.tag }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">观测人：</span>
              <span class="info-value">{{ record.observer }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">观测时间：</span>
              <span class="info-value fonts-DIN">{{ record.observationTime }}</span>
            </div>
          </div>
        </div>
        <div class="detail-layout" v-else>
          <div class="detail-image">
            <img class="img" :src="record.img" alt="默认图片">
          </div>
          <div class="detail-info">
            <div class="info-item">
              <span class="info-label">暂无数据</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import CardBox from '@/components/Global/CardBox.vue'
import {EventBus} from "../../utils/event-bus";
import WaveSurfer from "wavesurfer.js";

export default {
  components: {
    CardBox
  },
  created() {
    // EventBus.$on('sent-record', (message) => {
    //   this.record = message;
    //   if(this.record.fileType=='audio'){
    //     setTimeout(() => {
    //       this.initWaveSurfers()
    //     }, 2000)
    //   }else if(this.record.fileType=='video'){
    //     // this.initWaveSurfers()
    //   }
    //   // this.record.fileUrl="https://ui.ecoheze.com/weed/"+ this.record.fileUrl;
    // });
    EventBus.$on('sent-record', (message) => {
      if(message){
        this.record=message;
        let jsonObject = JSON.parse(message.phenologicalPeriodData);
        this.record.img=jsonObject[0].files.length>0?'https://ld.kedu.com.cn:4780/botanical-gardens/'+jsonObject[0].files[0].fileUrl:require("@/assets/img/default-plant.png");
        this.record.fileType='image';
      }

    })
  },
  data() {
    return {
      record:null,
      type:'hongwai',
      wavesurfer: null,
      isPlaying: false,
      autoplayAttempted: false,
      card: null,
      timeDisplay: null,
      speciesData: {
        // imageUrl: require('@/assets/img/bird.png'), // 这里设置默认图片或从props接收
        // name: '鸟',
        // deviceName: '红外10号 绿化示范区',
        // time: '2025-03-03'
      }
    }
  },
  methods: {
    updateSpeciesData(data) {
      this.speciesData = {
        name: data.name,
        deviceName: data.deviceName,
        time: data.time,
        imageUrl: data.imageUrl,
        type:data.type
      };
    },
    initWaveSurfers() {
      try {
        this.isPlaying = false
        this.autoplayAttempted = false

        const waveform = this.$refs.waveform1

        this.card = document.getElementById('card1')

        this.timeDisplay = document.getElementById('time1')


        this.wavesurfer = WaveSurfer.create({
          container: waveform,
          waveColor: '#4a90e2',
          progressColor: '#2c3e50',
          cursorColor: '#e74c3c',
          barWidth: 1,
          barRadius: 2,
          cursorWidth: 1,
          height: 50,
          barGap: 1,
          responsive: true,
          normalize: true,
          interact: false
        })

        this.wavesurfer.on('error', function(error) {
          console.error('WaveSurfer错误:', error)
        })

        this.wavesurfer.load(this.record.fileUrl);

        this.wavesurfer.on('ready', () => {
          this.updateTimeDisplay(0, this.wavesurfer.getDuration())

          if (this.autoplayAttempted) {
            this.autoplayAttempted = true

            setTimeout(() => {
              this.playAudio()
            }, 2000)
          }
        })

        this.wavesurfer.on('audioprocess', () => {
          this.updateTimeDisplay(this.wavesurfer.getCurrentTime(), this.wavesurfer.getDuration())
          this.updateProgressBar(this.wavesurfer.getCurrentTime() / this.wavesurfer.getDuration())
        })

        this.wavesurfer.on('finish', () => {
          this.isPlaying=false;
          this.playNextAudio();
        })


      } catch (error) {
        console.error('Error initializing wave surfers:', error)
      }
    },
    initVideoPlayers() {
      try {
        // 使用正确的选择器获取所有video元素
        const videoPlayers = document.querySelectorAll('.video-item video');
        if (videoPlayers && videoPlayers.length > 0) {
          videoPlayers.forEach(player => {
            if (player) {
              player.play().catch(error => {
                console.error('Error playing video:', error)
              })
            }
          })
        }
      } catch (error) {
        console.error('Error initializing video players:', error)
      }
    },
    loadAudio() {
      if (!this.wavesurfer) return
      this.wavesurfer.stop()
    },
    attemptAutoplay() {
      const playPromise = this.wavesurfer.play()

      if (playPromise !== undefined) {
        playPromise.then(() => {
          this.isPlaying = true
        })
                .catch(error => {
                  console.log('自动播放被阻止:', error)
                })
      }
    },
    updateActiveCard() {
      this.card.classList.remove('active')
      this.card.classList.add('active')
    },
    playAudio() {

      if (this.isPlaying) {
        this.isPlaying=false;
        this.wavesurfer.stop();
        this.updateActiveCard();
        return;
      }

      const playPromise = this.wavesurfer.play()
      if (playPromise !== undefined) {
        playPromise.then(() => {
          this.isPlaying = true
          this.card.classList.add('active')
        })
                .catch(error => {
                  console.error('播放失败:', error)
                })
      }
    },
    playNextAudio() {
      this.card.classList.remove('active')
      setTimeout(() => {
        this.playAudio()
      }, 3000)
    },
    updateTimeDisplay( currentTime, duration) {
      if (this.timeDisplay) {
        this.timeDisplay.textContent = `${this.formatTime(currentTime)} / ${this.formatTime(duration)}`
      }
    },
    updateProgressBar(progress) {
      const progressBar = document.getElementById(`progress1`)
      if(progressBar) {
        progressBar.style.width = `${progress * 100}%`
      }
    },
    formatTime(seconds) {
      const minutes = Math.floor(seconds / 60)
      const secs = Math.floor(seconds % 60)
      return `${minutes}:${secs < 10 ? '0' : ''}${secs}`
    }
  }
}
</script>

<style lang="scss" scoped>
.species-observation-detail {
  .species-observation-detail-content {
    padding: 10px;
    margin-top: 10px;
    height: 242px;
  }

  .detail-layout {
    display: flex;
    height: 100%;
    gap: 20px;
  }

  .detail-image {
    flex: 0 0 60%;
    height: 100%;
    border-radius: 4px;
    overflow: hidden;
    background: rgba(0, 24, 106, 0.2);

    video {
      width: 100%;
      height: 100%;
    }
  }

  .detail-info {
    flex: 1;
    padding: 20px;
    background: rgba(65, 123, 214, 0.19);
    border-radius: 4px;
  }

  .info-item {
    margin-bottom: 15px;
    font-size: 14px;
    color: #fff;

    &:last-child {
      margin-bottom: 0;
    }
  }

  .info-label {
    color: rgba(255, 255, 255, 0.8);
    margin-right: 8px;
  }

  .info-value {
    color: #07FFE5;
  }
}
.img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
.content-audios {
  display: flex;
  gap: 10px;
  justify-content: center;
  align-items: center;
  width: 300px;
  height: 90%;
}

.audio-card {
  width: 100%;
  height: 100%;
  overflow: hidden;
  box-shadow: 0 6px 12px rgba(0,0,0,0.1);
  transition: all 0.3s ease;
  background-color: white;
  position: relative;
  cursor: pointer;
  display: flex;
  flex-direction: column;
}

.audio-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0,0,0,0.15);
}

.audio-card.active {
  box-shadow: 0 0 0 3px #4a90e2, 0 10px 20px rgba(74, 144, 226, 0.3);
}

.audio-card.active::after {
  content: "正在播放";
  position: absolute;
  top: 10px;
  right: 10px;
  background-color: #4a90e2;
  color: white;
  padding: 3px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: bold;
}
/*.audio-img {*/
/*  width: 100%;*/
/*  height: 75%;*/
/*}*/
.audio-image {
  width: 100%;
  height: 75%;
  object-fit: fill;
}

.audio-content {
  height: 50px;
  display: flex;
  flex: 1;
  padding: 5px;
}

.audio-info {
  flex: 1;
  padding-right: 5px;
}

.audio-info h3 {
  padding-top: 5px;
  padding-left: 5px;
  margin: 0 0 8px 0;
  color: #2c3e50;
  font-size: 12px;
  height: 18px;
}

.audio-info p {
  margin: 0;
  color: #7f8c8d;
  font-size: 14px;
}

.waveform-container {
  width: 65%;
  height: 50px;
  background-color: #f1f3f4;
  border-radius: 6px;
  position: relative;
  overflow: hidden;
}

.waveform {
  width: 100%;
  height: 100%;
}

.progress-bar {
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  width: 0;
  background-color: rgba(74, 144, 226, 0.2);
  pointer-events: none;
}

.time-display {
  padding-left: 5px;
  font-size: 12px;
  color: #7f8c8d;
  margin-top: 5px;
  text-align: left;
}

.autoplay-message {
  text-align: center;
  color: #e74c3c;
  margin-bottom: 20px;
  font-size: 14px;
  display: none;
}

@media (max-width: 900px) {
  .audio-cards {
    flex-direction: column;
  }

  .audio-card {
    width: 100%;
    /*margin-bottom: 20px;*/
  }

  .waveform-container {
    width: 120px;
  }
}
</style>